/**
 * 
 */
package com.jd.event;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * @author luolishu
 * 
 */
public class EventTarget implements Delayed {
	private final long MILILI_ORIGIN = System.currentTimeMillis();
	private String id;

	private Date eventTime;

	private long time;
	
	private Event<?> event;

	public EventTarget(Event<?> event){
		this.id=event.getId();
		this.eventTime=event.getEventTime();
		this.setEventTime(eventTime);
		this.event=event;
	}
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Date getEventTime() {
		return eventTime;
	}

	public void setEventTime(Date eventTime) {
		this.eventTime = eventTime;
		this.time = this.eventTime.getTime() - System.currentTimeMillis();
	}

	public Event<?> getEvent() {
		return event;
	}

	public void setEvent(Event<?> event) {
		this.event = event;
	}

	public String toString() {
		return id + "-" + eventTime;
	}

	public int hashCode() {
		return new HashCodeBuilder().append(id).append(eventTime).toHashCode();
	}

	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!(obj instanceof EventTarget))
			return false;
		return (this.hashCode() == obj.hashCode());
	}

	final long now() {
		return System.currentTimeMillis() - MILILI_ORIGIN;
	}

	@Override
	public int compareTo(Delayed other) {
		if (other == this)
			return 0;
		if (other instanceof EventTarget) {
			EventTarget x = (EventTarget) other;
			long diff = eventTime.getTime() - x.eventTime.getTime();
			if (diff < 0)
				return -1;
			else if (diff > 0)
				return 1;
			else
				return 1;
		}
		long d = (getDelay(TimeUnit.MILLISECONDS) - other
				.getDelay(TimeUnit.MILLISECONDS));
		return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
	}

	@Override
	public long getDelay(TimeUnit unit) {
		long d = unit.convert((time - now()), TimeUnit.MILLISECONDS);
		return d;
	}

}
